package com.googlecode.aleverr.yafotkiclient.ui.adapters;

import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.googlecode.aleverr.yafotkiclient.ui.routines.PhotoLoader;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractPhotoAdapter<E> extends BaseAdapter implements PhotoLoader.OnPhotoLoadedListener {

    protected static final PhotoLoader PHOTO_LOADER = new PhotoLoader();

    static {
        PHOTO_LOADER.start();
    }

    Handler handler = new Handler();

    protected List<E> elements = new ArrayList<E>();

    @Override
    public int getCount() {
        return elements.size();
    }

    @Override
    public E getItem(int i) {
        if (i >= 0 && i < elements.size()) {
            return elements.get(i);
        }
        return null;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    public void update(List<E> newElements) {
        if (newElements != null) {
            elements = newElements;
            notifyDataSetChanged();
        }
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (view == null) {
            view = loadView(viewGroup);
        }
        E element = getItem(i);
        if (element != null) {
            Integer hashCode = (Integer) view.getTag();
            if (hashCode == null || hashCode != System.identityHashCode(element)) {
                Log.d("PhotoAdapter", "processElement: " + i);
                processElement(view, element);
                view.setTag(System.identityHashCode(element));
            }
        }
        return view;
    }

    protected abstract View loadView(ViewGroup viewGroup);

    protected abstract void processElement(View view, E element);

    @Override
    public void onPhotoLoaded(final View view, final Bitmap bitmap) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                assignBitmapToView(bitmap, view);
            }
        });
    }

    public abstract void assignBitmapToView(Bitmap bitmap, View view);
}
